package com.ts.api.module.channel.controller;

import com.gitee.apanlh.annotation.viewresolver.RequestParamVo;
import com.gitee.apanlh.util.algorithm.digest.MD5;
import com.gitee.apanlh.util.base.ChooseEq;
import com.gitee.apanlh.util.base.CollUtils;
import com.gitee.apanlh.util.base.Eq;
import com.gitee.apanlh.util.reflection.CopyUtils;
import com.gitee.apanlh.util.valid.IdcardUtils;
import com.gitee.apanlh.util.valid.ValidParam;
import com.gitee.apanlh.web.model.vo.RequestVO;
import com.gitee.apanlh.web.model.vo.ResultVO;
import com.ts.api.common.constant.BizEnum;
import com.ts.api.common.constant.channel.ChannelRegisterFieldEnum;
import com.ts.api.common.constant.common.SwitchEnum;
import com.ts.api.common.context.ChannelContext;
import com.ts.api.common.context.ChannelUserContext;
import com.ts.api.common.localcache.DistrictCache;
import com.ts.api.exp.BizException;
import com.ts.api.module.api.entity.ApiUserRequest;
import com.ts.api.module.channel.entity.ChannelRegisterField;
import com.ts.api.module.channel.entity.cache.ChannelCacheUser;
import com.ts.api.module.channel.entity.po.ChannelFlowConfigPO;
import com.ts.api.module.channel.entity.po.ChannelPO;
import com.ts.api.module.channel.entity.po.ChannelUserRegisterPO;
import com.ts.api.module.channel.entity.vo.ReqAnXinFenQiVO;
import com.ts.api.module.channel.service.ChannelConfigService;
import com.ts.api.module.channel.service.ChannelRegisterFieldService;
import com.ts.api.module.channel.service.ChannelResetFlowService;
import com.ts.api.module.channel.service.DoubleWriteUserService;
import com.ts.api.module.channel.service.H5InfoFlowService;
import com.ts.api.module.common.entity.DistrictPO;
import com.ts.api.module.common.service.UserRealAuthService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * h5信息流
 *
 * @author caoxin
 */
@RestController
@RequestMapping("/channel/h5InfoFlow")
public class H5InfoFlowController {

    @Autowired
    private ChannelResetFlowService channelResetFlowService;
    @Autowired
    private H5InfoFlowService h5InfoFlowService;
    @Autowired
    private ChannelRegisterFieldService channelRegisterFieldService;
    @Autowired
    private UserRealAuthService userRealAuthService;
    @Autowired
    private DoubleWriteUserService doubleWriteUserService;
    @Autowired
    private ChannelConfigService channelConfigService;

    /**
     * 安心分期
     */
    @PostMapping("/axfq")
    public ResultVO<Object> axfq(@RequestParamVo RequestVO requestVO) {

        this.channelResetFlowService.track();

        ChannelPO channelPO = ChannelContext.get();

        // 获取用户信息
        ChannelCacheUser channelUser = ChannelUserContext.get();

        // 获取享用米对象
        ReqAnXinFenQiVO axfqVO = requestVO.toBean(ReqAnXinFenQiVO.class);

        // 转化ApiUserInfo对象
        ApiUserRequest apiUserRequest = CopyUtils.copy(axfqVO, ApiUserRequest.class);
        apiUserRequest.setLoanChannelId(channelPO.getId());
        apiUserRequest.setPhoneMd5(MD5.create().digestToHex(channelUser.getPhone()));
        apiUserRequest.setPhone(channelUser.getPhone());

        //  校验城市
        if (ValidParam.isEmpty(apiUserRequest.getAreaCode()) || ValidParam.isEmpty(apiUserRequest.getCity())) {
            BizException.fastFail(BizEnum.EMPTY);
        }
        //  前端传的城市名称有可能是简写，要转一下，避免分发的时候造成问题
        DistrictPO districtPO = DistrictCache.getByName(apiUserRequest.getCity());
        apiUserRequest.setAreaCode(districtPO.getCode());
        apiUserRequest.setCity(districtPO.getName());

        List<ChannelRegisterField> listChannelRegisterField = channelRegisterFieldService.list(ChannelContext.getId());
        List<ChannelRegisterField> findUserName = CollUtils.find(listChannelRegisterField, t -> Eq.str(t.getMappingName(), ChannelRegisterFieldEnum.USER_NAME.getMappingName()));
        List<ChannelRegisterField> findIdcard = CollUtils.find(listChannelRegisterField, t -> Eq.str(t.getMappingName(), ChannelRegisterFieldEnum.IDCARD.getMappingName()));
        if (ValidParam.isNotEmpty(findUserName) && ValidParam.isEmpty(apiUserRequest.getUserName())) {
            BizException.fastFail(BizEnum.EMPTY);
        }
        if (ValidParam.isNotEmpty(findIdcard) && ValidParam.isEmpty(apiUserRequest.getIdcard())) {
            BizException.fastFail(BizEnum.EMPTY);
        }
        if (ValidParam.isNotEmpty(findIdcard) && ValidParam.isNotEmpty(apiUserRequest.getIdcard())) {
            boolean valid = IdcardUtils.valid(apiUserRequest.getIdcard());
            if (!valid) {
                return ResultVO.fail("认证失败,请输入正确的身份证");
            }
            Integer age = IdcardUtils.getAge(apiUserRequest.getIdcard());
            apiUserRequest.setAge(age.toString());
            String idcardSex = IdcardUtils.getGender(apiUserRequest.getIdcard());
            String sex = ChooseEq.create(idcardSex)
                    .when("男", "0")
                    .when("女", "1")
                    .end();
            apiUserRequest.setSex(sex);
        }

        if (ValidParam.isNotEmpty(findUserName) && ValidParam.isNotEmpty(findIdcard)) {
            // 基础验证
            boolean valid = IdcardUtils.valid(apiUserRequest.getIdcard());
            if (!valid) {
                return ResultVO.fail("认证失败,请输入正确的身份证");
            }

            //  验证渠道是否二要素验证
            ChannelFlowConfigPO channelFlowConfigPO = channelConfigService.getFlowConfigByChannelId();
            if (SwitchEnum.hasEnable(channelFlowConfigPO.getEnableTwoElement())) {
                //  二要素检测
                Boolean nameAndIdcardFlag = userRealAuthService.nameAndIdcard(apiUserRequest.getUserName(), apiUserRequest.getIdcard());
                //  更新二要素校验状态
                ChannelUserRegisterPO updateUserRegisterPO = new ChannelUserRegisterPO();
                updateUserRegisterPO.setId(channelUser.getUserId());
                if (nameAndIdcardFlag) {
                    updateUserRegisterPO.setTwoElementStatus(1);
                } else {
                    updateUserRegisterPO.setTwoElementStatus(0);
                }
                doubleWriteUserService.updateUser(updateUserRegisterPO);

                if (!nameAndIdcardFlag) {
                    return ResultVO.fail("认证失败,请输入正确的信息");
                }
            }
        }

        this.h5InfoFlowService.save(apiUserRequest);

        return ResultVO.suc(apiUserRequest);
    }

}
